<template>
  <!--<div style="margin: 10px 5px">-->
  <!--  <el-button type="primary" @click="exit">新增</el-button>-->
  <!--  <el-button type="primary">其他</el-button>-->
  <!--</div>-->
  <div>
    <!--    header-->
    <div style="height: 50px; line-height: 50px; border-bottom: 1px solid #ccc; display: flex">
      <div style="width: 500px; padding-left: 30px; font-weight: bold; color: dodgerblue">
        工程资料管理系统——四季花园二期项目（待二次开发）
      </div>
      <div style="flex: 1">

      </div>
      <div style="width: 300px">
        <el-dropdown>
    <span class="el-dropdown-link" style="margin-top: 10px; margin-right: 20px;">
      {{ this.componyName }}
      <el-icon class="el-icon--right">
        <arrow-down/>
      </el-icon>
    </span>
          <template #dropdown>
            <el-dropdown-menu>
              <!--<el-dropdown-item>基本信息</el-dropdown-item>-->
              <el-dropdown-item @click="">公司基本信息（待二次开发）</el-dropdown-item>
              <el-dropdown-item @click="skip('/')">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

      </div>
    </div>

    <div style="display:flex;">
      <!--侧边栏-->
      <div>
        <el-menu
            style="width: 150px"
            default-active="2"
            class="el-menu-vertical-demo"
        >
          <el-sub-menu index="2">
            <template #title>
              <span @click="list" style="margin-left: -20px">文件管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="2-1" @click="listfile('公司资质')">文件清单</el-menu-item>
              <el-menu-item index="2-1" @click="listfile('公司资质')">文件统计(待二次开发)</el-menu-item>
              <!--<el-menu-item index="2-1" @click="findByType('公司资质')">公司资质</el-menu-item>-->
              <!--<el-menu-item index="2-2" @click="findByType('公司资质')">公司资质</el-menu-item>-->
              <!--<el-menu-item index="2-3" @click="findByType('人员证件')">人员证件</el-menu-item>-->
              <!--<el-menu-item index="2-4" @click="findByType('员工合同')">员工合同</el-menu-item>-->
              <!--<el-menu-item index="2-5" @click="findByType('工作联系单')">工作联系单</el-menu-item>-->
              <!--<el-menu-item index="2-6" @click="findByType('整改单')">整改通知单</el-menu-item>-->
              <!--<el-menu-item index="2-7" @click="findByType('旁站记录')">旁站记录</el-menu-item>-->
              <!--<el-menu-item index="2-8" @click="findByType('土建')">土建</el-menu-item>-->
              <!--<el-menu-item index="2-9" @click="findByType('安装')">安装</el-menu-item>-->
              <!--<el-menu-item index="2-10" @click="findByType('其他')">其他</el-menu-item>-->
            </el-menu-item-group>
          </el-sub-menu>
          <el-sub-menu index="3">
            <template #title>
              <span @click="list" style="margin-left: -20px">流程管理</span>
            </template>
            <el-menu-item-group>
              <el-menu-item index="3-1" @click="findByState(0)">我的流程</el-menu-item>
            </el-menu-item-group>
          </el-sub-menu>
        </el-menu>
      </div>

      <!--内容区-->
      <div style="width: 100%; margin-top: 20px">
        <div style=" width: 100%;font-size: medium; margin-bottom: 10px">
          <el-button type="primary" @click="sendFile" style="width: 8%;  float: left; margin-left: 2%">新增文件
          </el-button>
          <el-input v-model="search" style="width: 15%;margin-left: 10%;float: left" placeholder="此处通过文件名查找"/>
          <el-button style="width: 8%; margin-left: 1%;float: left" type="primary" @click="listBySearch">查找</el-button>
        </div>

        <el-table :data="tableData" stripe style="width: 100%">
          <!--<el-table-column-->
          <!--    prop="id"-->
          <!--    label="ID"-->
          <!--    sortable-->
          <!--&gt;-->
          <!--</el-table-column>-->
          <el-table-column
              prop="name"
              label="文件名"
              min-width="100px"

          >
          </el-table-column>
          <el-table-column
              prop="date"
              label="收/发&nbsp;时间"
              :formatter="formatTime"
              min-width="100px"
              align="center">

          </el-table-column>

          <el-table-column
              prop="send"
              label="发文单位"
              min-width="100px"
              align="center">
          </el-table-column>

          <el-table-column
              prop="accept"
              label="收文单位"
              min-width="100px"
              align="center">
          </el-table-column>

          <el-table-column
              prop="type"
              label="文件类型"
              align="center">
          </el-table-column>

          <!--<el-table-column-->
          <!--    prop="state"-->
          <!--    label="流程状态">-->
          <!--</el-table-column>-->

          <el-table-column
              label="预览 / 下载">
            <template #default="scope">
              <button @click="pngOpen(scope.row.id)">
                <el-icon>
                  <Document/>
                </el-icon>
              </button>
              &nbsp;
              <button @click="handleDownload(scope.row.id)">
                <el-icon>
                  <Download/>
                </el-icon>
              </button>

            </template>
          </el-table-column>


          <el-table-column fixed="right" label="操作" width="145">
            <template #default="scope">
              <!--<el-button type="text" @click="handleEdit(scope.row)"-->
              <!--&gt;编辑-->
              <!--</el-button-->
              <!--&gt;-->
              <el-button type="text" @click="getFileById(scope.row.id)"
              >编辑
              </el-button
              >
              <el-popconfirm @confirm="handleDel(scope.row.id)" title="确认删除？">
                <template #reference>
                  <el-button>删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!--图片展示区-->
        <!--<el-dialog-->
        <!--    :title="title"-->
        <!--    v-model="viewVisible"-->
        <!--    width="60%"-->
        <!--    height="60%"-->
        <!--    center-->
        <!--&gt;-->
        <el-dialog title="文件预览" v-model="displaydialogVisible" width="100%">
            <div class="demo-image__preview">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="urlList[0]"
                  :preview-src-list="urlList"
                  :initial-index="urlList.length - 1"
                  fit="cover"
              />
            </div>
        </el-dialog>
        <!--调整出url-->
        <!--<el-image width="80%" style="margin-left:10%" v-bind:src="pngUrl" alt="" />-->
        <!--</el-dialog>-->


        <!--发文框-->
        <el-dialog title="添加文件" v-model="sendFiledialogVisible" width="70%">
          <el-form :model="form" :rules="rules" ref="form" label-width="120px" enctype="form-data">

            <el-form-item label="文件" prop="files">
              <input type="file" ref="file" v-on:change="handleFileUpload($event)" multiple>
            </el-form-item>

            <el-form-item label="事宜" prop="name">
              <el-input v-model="form.name" style="width: 80%" placeholder="请输入文件名称"></el-input>
            </el-form-item>

            <el-form-item label="发文类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择文件类型">
                <!--                后期可自动获取-->
                <el-option label="工作联系单" value="工作联系单"/>
                <el-option label="整改通知单" value="整改通知单"/>
              </el-select>
            </el-form-item>

            <el-form-item label="文件大小" prop="size">
              <el-input v-model="form.size" placeholder="选择文件后自动填入" disabled/>
            </el-form-item>

            <el-form-item label="发文单位" prop="send">
              <el-input v-model="form.send" disabled/>
            </el-form-item>

            <el-form-item label="收文单位" prop="accept">
              <el-input v-model="form.accept" placeholder="如仅存档可不填" style="width: 80%"></el-input>
            </el-form-item>

            <el-form-item label="抄送单位(选填)" prop="cc">
              <el-input v-model="form.cc" placeholder="如仅存档可不填" style="width: 80%"></el-input>
            </el-form-item>

            <el-form-item label="发文日期" prop="date">
              <div class="block">
                <el-date-picker
                    v-model="form.date"
                    type="datetime"
                    placeholder="请选择创建时间"
                    :formatter="formatTime"
                />
                <span class="demonstration" style="font-size: small"> {{ value1 }}</span>
              </div>
            </el-form-item>

            <el-form-item label="文件摘要">
              <el-input v-model="form.introduce" placeholder="可选填" type="textarea"/>
            </el-form-item>

          </el-form>

          <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="sendFiledialogVisible = false">取 消</el-button>
                      <el-button type="submint" @click="save">发 送</el-button>
                    </span>
          </template>

        </el-dialog>

        <!--    添加分页导航-->
          <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                @updata:current-page.sync="handleCurrentChange"
                @update:page-size.sync="handlePageSizeChange"
                @size-change="handlePageSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[5, 10, 20, 30]"
                :small="false"
                :disabled="false"
                :background="false"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            />
          </div>

      </div>
    </div>
  </div>
</template>

<script>
import Header from "@/components/Header";
import Aside from "@/components/Aside";
import HeaderUserPage from "@/components/HeaderUserPage";
import request from "@/utils/request";
import axios from "axios";
import {pngYL} from "@/utils/pngYL";
import JSZip from "jszip";
import moment from "moment";


// 文件上传
export function postUpload(file) {
  return axios({
    url: "/api/fileUpload",
    method: 'post',
    data: file,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

export default {
  name: "FileManagement",
  components: {HeaderUserPage, Aside, Header},
  created() {
    this.listfileByComName()
    // this.list();
  },

  data() {
    return {
      //存放后端校验错误信息
      serverValidErrors: {},


      search: '',
      sendFiledialogVisible: false,
      form: {},//定义一个空表单
      componyName: this.$route.query.componyName,
      componyId: this.$route.query.componyId,
      tableData: [],
      user: {},
      images: [],
      FormData: {},
      files: {},
      msg: '',
      type: '',
      state: '',
      rules: {
        name: [
          {required: true, message: "请填写文件主要信息", trigger: "blur"}
        ],
        type: [
          {required: true, message: "请选择发文类型", trigger: "blur"}
        ],
        accept: [
          {required: false, message: "请输入收文单位", trigger: "blur"}
        ],
        cc: [
          {required: false, message: "请输入抄送单位", trigger: "blur"}
        ],
        date: [
          {required: true, message: "请选择日期", trigger: "blur"}
        ]
      },
      pngUrl: '',
      title: "",
      displaydialogVisible: false,
      urlList: [],
      zip: null,
      // 分页参数
      currentPage: 1,
      pageSize: 10,
      total: 10,
    }
  },
  methods: {
    resetMessage() {
      this.$message({
        type: "success",
        message: ''
      })
    },
    listBySearch() {
      request.get("/api/listFileBySearch", {
        params: {//指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          componyName: this.componyName,
          search: this.search
        }
      }).then(res => {//处理返回的分页信息
        this.tableData = res.extend.pageInfo.list
        this.total = (Number)(res.extend.pageInfo.total)
      })
    },
    //格式化时间
    formatTime(row, column) {
      let date = row[column.property];
      if (date === undefined) {
        return ''
      }
      return moment(date).format("yyyy-MM-DD, HH:mm:ss")
    },
    async pngOpen(id) {
      pngYL(id).then((res) => {
        // console.log("res=>", res)
        this.urlList = []
        let _that = this
        let zip = new JSZip();
        zip.loadAsync(res).then(async res => {
          for (let key in res.files) {
            if (!res.files[key].dir) {  // 判断是否是目录
              if (/\.(png)$/.test(res.files[key].name)) { // 判断是否是png文件
                let base = await zip.file(res.files[key].name).async('base64') // 以base64输出文本内容
                // Base64 转 File 对象
                let result = this.dataURLtoFile(base, res.files[key].name)
                // console.log('最终解压后的File对象',result)
                let reader = new FileReader();
                reader.readAsDataURL(result)
                //当读取成功后触发
                reader.onload = function (e) {
                  let arr = e.target.result.split(',')
                  // console.log("arr=> ", arr)
                  let data = window.atob(arr[1])
                  // console.log("data=> ", data)
                  let mime = arr[0].match(/:(.*?);/)[1]
                  // console.log("mime=> ", mime)
                  let ia = new Uint8Array(data.length)
                  // console.log("ia=> ", ia)
                  for (let i = 0; i < data.length; i++) {
                    ia[i] = data.charCodeAt(i)
                  }
                  let url = window.URL.createObjectURL(new Blob([ia], {type: "image/png"}));
                  _that.urlList.push(url)
                }
              }
            }
          }
          this.displaydialogVisible = true
          // console.log("urlList=>", this.urlList)
        })
      })
    },
    dataURLtoFile(dataURL, fileName, fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
      /**
       * 注意：【不同文件不同类型】，例如【图片类型】就是`data:image/png;base64,${dataURL}`.split(',')
       * 下面的是【excel文件(.xlsx尾缀)】的文件类型拼接，一个完整的 base64 应该
       * 是这样的,例如： 
       */
      const arr = `data:${fileType};base64,${dataURL}`.split(',')
      // console.log("arr=> ", arr)
      const mime = arr[0].match(/:(.*?);/)[1]
      // console.log(arr[1])
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      let blob = new File([u8arr], fileName, {type: mime})
      return blob
    },
    //已经可以一般展示图片的方法
    pngOpen1(id) {

      pngYL(id).then((res) => {
        console.log(res)
        let blob = new Blob([res]);   // 返回的文件流数据
        console.log("blob=>", blob)
        let url = window.URL.createObjectURL(blob);  // 将他转化为路径
        console.log("url=>", url)
        // window.open(url)

        this.viewVisible = true;  //在当前页面弹框打开
        this.pngUrl = url;
        // const binaryData = [];
        // binaryData.push(res.data);
        // let url = window.URL.createObjectURL(
        //     new Blob(binaryData, {type: "image/png"})
        // );
        // let file = new window.File(new Blob(binaryData, {type: "image/png"}), 'aaa,png', {type: 'image/png'})

        // this.pngUrl = file;
        // console.log("pngUrl=>", this.pngUrl)
        // 新页面打开
        // alert(this.pngUrl)

        // window.open(url);
      });
    },
    handleDownload(id) {
      axios.get("/api/fileDown/" + id, {
        responseType: 'blob',//设置返回类型
        //设置token
        // headers: {
        //   Authorization: store.getters['user/accessToken'],
        // },
      },).then((res) => {
        //创建一个a标签元素
        const link = document.createElement('a');
        try {
          //获取到blob
          let blob = new Blob([res.data], {type: "application/octet-stream"});

          // let _fileName = res.headers['content-disposition'].split(';')[1].split('=')[1];//文件名，中文无法解析的时候会显示 _(下划线),生产环境获取不到
          let contentDisposition = res.headers['content-disposition'];
          // fileName必用这种方式进行解析，否则乱码
          let _fileName = window.decodeURI(contentDisposition.substring(contentDisposition.indexOf('=') + 1));
          link.style.display = 'none';
          // 兼容不同浏览器的URL对象
          const url = window.URL || window.webkitURL || window.moxURL;
          link.href = url.createObjectURL(blob);
          link.setAttribute('download', _fileName.substring(_fileName.lastIndexOf('_') + 1));
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          url.revokeObjectURL(link.href);//销毁url对象
        } catch (e) {
          console.log('下载的文件出错', e)
        }
      }).catch(() => {

      })
    },
    skip(url) {
      this.$router.push({path: url});
    },
    listfileByComName() {
      request.get("/api/listFile", {
        params: {//指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          componyName: this.componyName
        }
      }).then(res => {//处理返回的分页信息
        console.log(res)
        console.log(res.extend.pageInfo.total)
        this.tableData = res.extend.pageInfo.list
        this.total = (Number)(res.extend.pageInfo.total)
      })
    },
    list() {
      request.get("/api/listFileBySearchOrType", {
        params: {//指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search: this.search,
          type: this.type,
          componyName: this.componyName
        }
      }).then(res => {//处理返回的分页信息
        console.log(res)
        console.log(res.extend.pageInfo.total)
        this.tableData = res.extend.pageInfo.list
        this.total = (Number)(res.extend.pageInfo.total)
      })
    },
    findByType(type) {
      this.type = type
      this.search = ''
      // this.list()
      request.get("/api/findByType", {
        params: {//指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          type: this.type,
          componyName: this.componyName
        }
      }).then(res => {//处理返回的分页信息
        // this.tableData = res.extend.files
        this.tableData = res.extend.files
        this.page_count = res.data.total
      })
    },
    findByState(state) {
      this.state = state
      this.search = ''
      // this.list()
      request.get("/api/myProcess/" + this.componyId, {
        params: {//指定请求携带的参数
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          state: this.state,
          componyName: this.componyName
        }
      }).then(res => {//处理返回的分页信息
        // this.tableData = res.extend.files
        this.tableData = res.extend.files
        this.total = res.data.total
      })
    },
    sendFile() {
      this.form.send = this.componyName
      this.sendFiledialogVisible = true;

      this.files = ''
      //清空上次前端校验的信息
      this.$refs['form'].resetFields()
      // this.$refs['form'].resetFields()

      this.serverValidErrors = {}

    },
    handleDel(id) {
      request.delete("/api/del/" + id).then(res => {
        if (res.code === 200) {
          if (res.code === 200) {
            //提示一个成功框
            this.$message({
              type: "success",
              message: res.msg

            })
          } else {
            //提示一个失败框
            this.$message({
              type: "error",
              message: res.msg
            })
          }
          this.list()
        }
      })
    },
    save() {
      if (this.form.id) {
        request.post("/api/update", this.form).then(res => {
          if (res.code === 200) {
            //提示一个成功框
            this.$message({
              type: "success",
              message: "更新成功"
            })
            this.sendFiledialogVisible = false
          } else {
            //提示一个成功框
            this.$message({
              type: "error",
              message: "更新失败"
            })
          }

          this.list()

        })
      } else {
        // this.onUpload(this.FormData)
        postUpload(this.FormData).then((res) => {
          this.form.url = res.data.extend.urlList
          this.$message.success('文件已上传完成，')
          request.post("/api/saveFileInfo", this.form).then(res => {
            this.sendFiledialogVisible = false
            this.list()
          })
        }).catch((e) => {
          this.$message.error(e.message)
        })

      }
    },
    // 获取文件
    handleFileUpload(event) {
      // 阻止发生默认行为
      event.preventDefault();
      let formData = new FormData()
      let files = this.$refs.file.files
      // 遍历files加入formdata对象
      for (const file of files) {
        formData.append('file', file)
      }
      // 控制文件大小（单次）
      let totalSize = 0
      for (let i = 0; i < this.$refs.file.files.length; i++) {
        totalSize = totalSize + this.$refs.file.files[i].size;
      }
      if (totalSize > (50 * 1024 * 1024)) {
        return false
      }
      this.form.size = (totalSize / 1024 / 1024).toFixed(2) + ' MB'
      // 调用上传方法
      this.FormData = formData
      // this.onUpload(formData)
    },
    getFileById(id) {
      request.get("/api/find?id=" + id).then(res => {

        this.form = res.extend.file
        this.sendFiledialogVisible = true
      })
    },
    handleCurrentChange(pageNum) {
      this.currentPage = pageNum
      this.listfileByComName()
    },
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.listfileByComName()
    }
  }


// watch: {
//   '$route': 'list'
// }
}

</script>

<style scoped>
* {
  font-size: large;
}
</style>